# !/usr/bin/env python
# coding:utf-8
"""
    Author = 上善若水(QQ:564667570)
    Affiliation = Institute of Subtropical Agriculture, Chinese Academy of Sciences
    Time = '2018-3-4, 20:45'
"""

# 1. Installing the Python and SciPy platform.
# 2. Loading the dataset.
# 3. Summarizing the dataset.
# 4. Visualizing the dataset.
# 5. Evaluating some algorithms.
# 6. Making some predictions.

# Load libraries
import pandas
from pandas.plotting import scatter_matrix

import matplotlib.pyplot as plt

from sklearn import model_selection
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC

# Load dataset
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']
dataset = pandas.read_csv(url, names=names)

# Summarize the dataset
# dimensions of dataset
# shape
# print(dataset.shape)

# Peek at the data
# print(dataset.head(5))

# descriptions
# print(dataset.describe())

# Class Distribution
print(dataset.groupby('class').size())

# Univariate Plots

# box and whisker plots
# dataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False)
# plt.show()

# # Histograms
# dataset.hist()
# plt.show()

# # Scatter plot matrix
# scatter_matrix(dataset)
# plt.show()

"""
Here is what we are going to cover in this step:

    Separate out a validation dataset.
    Set-up the test harness to use 10-fold cross validation.
    Build 5 different models to predict species from flower measurements
    Select the best model.
"""

# Split-out validation dataset
array = dataset.values
X = array[:,0:4]
Y = array[:,4]
validation_size = 0.20
seed = 7
X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=validation_size, random_state=seed)

# Test Harness
# Test options and evaluation metric
seed = 7
scoring = 'accuracy'

"""We are using the metric of ‘accuracy‘ to evaluate models.
 This is a ratio of the number of correctly predicted instances 
 in divided by the total number of instances in the dataset multiplied
  by 100 to give a percentage (e.g. 95% accurate). We will be using the 
  scoring variable when we run build and evaluate each model next."""

# methods for machine learning
# Logistic Regression(LR)
# Linear Discriminant Analysis(LDA)
# K - Nearest Neighbors(KNN).
# Classification and Regression Trees(CART).
# Gaussian Naive Bayes(NB).
# Support Vector Machines(SVM).

# Spot check algorithms
models =[]
models.append(('LR', LogisticRegression()))
models.append(('LDA', LinearDiscriminantAnalysis()))
models.append(('KNN', KNeighborsClassifier()))
models.append(('CART',DecisionTreeClassifier()))
models.append(('NB', GaussianNB()))
models.append(('SVM', SVC()))

# evaluate each model in turn
results = []
names = []
for name, model in models:
    kfold = model_selection.KFold(n_splits=10, random_state=seed)
    cv_results = model_selection.cross_val_predict(model, X_train, Y_train, cv=kfold)
    results.append(cv_results)
    names.append(name)
    msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std())
    print(msg)

# Compare Algorithms
fig = plt.figure()
fig.suptitle('Algorithm Comparison')
ax = fig.add_subplot(111)
plt.boxplot(results)
ax.set_xticklabels(names)
plt.show()